<?php
namespace app\admin\controller\system;
use app\admin\controller\AuthController;
use app\admin\model\system\SysmenuModel;
use app\admin\model\system\SysroleModel;
use app\admin\validate\system\SysroleValidate;
use app\common\service\system\SysmenuService;
use app\common\service\system\SysroleService;
use think\facade\Db;

class SysroleController extends AuthController
{
    public function index()
    {
        if (!$this->isPost) {
            return $this->fetch();
        } else {
            $sysroleModel = new SysroleModel();
            $page = input('param.page');
            $pageSize = input('param.pageSize');
            $sysrolelist = $sysroleModel::with(["menus", 'users'])->orderRaw('CONVERT(title USING gbk)')->select();
            // return json(['rows' => $sysrolelist->toArray()['data'], 'total' => $sysrolelist->total()]);
            $this->success("成功！", "", $sysrolelist);
        }
    }
    public function add()
    {
        if ($this->isPost) {
            $params = input('post.');
            $menuids = input('post.menuids');
            if (empty($menuids)) {
                $this->error("请选择权限！", "", $params);
                exit;
            }
            $validate = new SysroleValidate();
            if (!$validate->check($params)) {
                $this->error($validate->getError());
                exit;
            }
            $sysroleModel = new SysroleModel();
            $insertid = $sysroleModel->insertGetId($params);
            $sysrole = SysroleModel::find($insertid);
            $sysrole->menus()->detach();//删除关联中间表数据
            $sysrole->menus()->saveAll($menuids);
            $this->success("成功！", "", $params);
        } else {
            return $this->fetch();
        }
    }
    public function edit()
    {
        if ($this->isPost) {
            $params = input('post.');
            $menuids = input('post.menuids');
            if (empty($menuids)) {
                $this->error("请选择权限！", "", $params);
                exit;
            }
            SysroleModel::update($params);
            $sysrole = SysroleModel::find($params['id']);
            $sysrole->menus()->detach();//删除关联中间表数据
            $sysrole->menus()->saveAll($menuids);
            // Db::name('sysrole_menu')->where('role_id', $params['id'])->delete();
            // Db::name('sysrole_menu')->insertAll($data);
            $this->success("成功！", "", $params);
        } else {
            $this->assign('rolelist', SysroleService::getAllList());
            $this->assign('menulist', SysmenuService::getAllList());
            return $this->fetch();
        }
    }
    public function delete()
    {
        $id = input('param.ids');
        $sysmodel = new SysroleModel();
        $res = $sysmodel->yqDeleteByIds(explode(',', $id));
        $this->success("成功！", "", $res);
    }
}